package com.bw.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.bean.TradePaymentWindowBean;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import com.bw.gmall.realtime.utils.TimestampLtz3CompareUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Date;

/*
*
uid 分组     取出第一次的
*
*
* */
//从 Kafka 读取交易域支付成功主题数据，统计支付成功独立用户数和首次支付成功用户数。
public class DwsTradePaymentSucWindow_a {

    public static void main(String[] args) throws Exception {

       //1.获取流式环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2.设置并行度
        env.setParallelism(1);
        //3.设置检查点

        //4.加载数据
        DataStreamSource<String> addSource = env
                .addSource(MyKafkaUtil.getFlinkKafkaConsumer("dwd_trade_pay_detail_suc", "dwd_trade_pay_detail_suc_xx"));

        //5.去重
        SingleOutputStreamOperator<JSONObject> map = addSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {

                out.collect(JSONObject.parseObject(value));
            }
        });
        //6.根据订单明细去重
        SingleOutputStreamOperator<JSONObject> process = map.keyBy(a -> a.getString("order_detail_id"))
                .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
                    ValueState<JSONObject> valueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        valueState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("valuestate", JSONObject.class));
                    }

                    @Override
                    public void processElement(JSONObject value, Context ctx, Collector<JSONObject> out) throws Exception {
                        JSONObject v = valueState.value();
                        if (v == null) {
                            valueState.update(value);
                            ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000l);
                        } else {
                            String stateDate = v.getString("row_op_ts");
                            String jlDate = value.getString("row_op_ts");
                            if (TimestampLtz3CompareUtil.compare(stateDate, jlDate) != 1) {
                                valueState.update(value);
                            }


                        }
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<JSONObject> out) throws Exception {
                        super.onTimer(timestamp, ctx, out);
                        JSONObject value = valueState.value();
                        out.collect(value);
                        valueState.clear();

                    }
                });

//        从 Kafka 读取交易域支付成功主题数据，统计支付成功独立用户数和首次支付成功用户数。
        SingleOutputStreamOperator<JSONObject> wt = process.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2l))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return DateFormatUtil.toTs(element.getString("callback_time"), true);
                    }
                }));

        //设置水位线  callback_time
        //key by   userid   processs      判断记录是否是独立   是否是首次     存入到对象中  放行
        SingleOutputStreamOperator<TradePaymentWindowBean> process1 = wt.keyBy(a -> a.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradePaymentWindowBean>() {

                    ValueState<String> valueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("valueState", String.class));

                    }

                    @Override
                    public void processElement(JSONObject value, Context ctx, Collector<TradePaymentWindowBean> out) throws Exception {

                        String jlDate = value.getString("callback_time").split(" ")[0];
                        String stateDate = valueState.value();

                        Long uvCount = 0l;
                        Long firstCount = 0l;

                        if (stateDate == null) {
                            uvCount = 1l;
                            firstCount = 1l;
                            valueState.update(jlDate);
                        } else {
                            if (!stateDate.equals(jlDate)) {
                                uvCount = 1l;
                                firstCount = 0l;
                                valueState.update(jlDate);
                            }
                        }


                        out.collect(new TradePaymentWindowBean("", "", uvCount, firstCount, null));

                    }
                });
        //windowall  聚合
        SingleOutputStreamOperator<TradePaymentWindowBean> reduce = process1.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradePaymentWindowBean>() {
                    @Override
                    public TradePaymentWindowBean reduce(TradePaymentWindowBean value1, TradePaymentWindowBean value2) throws Exception {
                        value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                        value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                        ;
                        return value1;
                    }
                }, new ProcessAllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                    @Override
                    public void process(Context context, Iterable<TradePaymentWindowBean> elements, Collector<TradePaymentWindowBean> out) throws Exception {
                        TradePaymentWindowBean next = elements.iterator().next();
                        long end = context.window().getEnd();
                        long start = context.window().getStart();

                        next.setStt(DateFormatUtil.toYmdHms(start));
                        next.setEdt(DateFormatUtil.toYmdHms(end));
                        next.setTs(System.currentTimeMillis());
                        out.collect(next);

                    }
                });
        //获取 开始时间和结束时间
        reduce.print("-------------------------->");
        //存入clickhouse



        env.execute();


    }

}
